<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:include="include :: header('商品库')"/>
    <th:block th:include="include :: businessCSS"/>
    <style>

        .preservationBtn{padding: 10px;text-align: center;}
        .preservationBtn input{font-size: 16px;background-color: rgb(80, 138, 238);color: #fff;border: none;padding: 5px 30px;border-radius: 10px;cursor: pointer;}


    </style>
</head>
<body class="no-skin">
<div class="main-container" id="main-container">
    <div class="main-content">
        <form class="layui-form head-form">
            <div class="topbtns" th:if="${vType} == 0">
                <th:block th:include="include :: business_btn"/>
            </div>
            <div class="north">
                <div class="forminput"></div>
            </div>
            <div style="width: 100%;height: 10px;background: #f6f6f6;"></div>
            <div>
                <table class="layui-hide" id="dhtable" lay-filter="mjtable"></table>
                <script type="text/html" id="zjtoolbar">
                    <div style="padding: 16px;display: flex;justify-content: space-between;">
                        <div style="font-weight: 700;font-size: 18px;">子件清单</div>
                        <div>
                            <!-- <button class="layui-btn layui-btn-normal dhicon" th:classappend="${enableEdit} == 1 ?'':'layui-btn-disabled'" type="button" th:disabled="${enableEdit} == 1 ?false:true" lay-event="addbtn" id="btn-sh">新增</button> -->
                            <!-- <button class="layui-btn layui-btn-danger dhicon" th:classappend="${enableEdit} == 1 ?'':'layui-btn-disabled'" type="button" th:disabled="${enableEdit} == 1 ?false:true" lay-event="mjbtn_save" id="btn-sh">删除</button> -->
                        </div>
                    </div>
                </script>
            </div>
            <th:block th:include="include :: pageFooter" th:if="${vType} == 0 "/>
            <div class="layui-form-item preservationBtn" th:if="${vType} != 0 and ${vType} != 3 ">
                <input type="button" lay-submit lay-filter="btn-add" id="btn-add" value="保存">
            </div>
        </form>
    </div>
</div>

<!-- 表格操作区 -->
<script type="text/html" id="barDh">
    <a class="layui-btn layui-btn-danger layui-btn-xs dhicon dh-remove" lay-event="del"
       shiro:hasPermission="business:productbasis:delete">&nbsp;删除</a>
</script>

<script type="text/html" id="stockQty">
    <span style="margin-right: 25px;">{{typeof d.stockQty !== 'undefined' && d.stockQty !== null?d.stockQty:''}}</span>
    <i class="layui-icon layui-icon-more getMore"
       onclick="getMore('stockQty',{{d.LAY_TABLE_INDEX}},'库存数量','tcc_stockcontrol','')"
       style="float:right;z-index:999"></i>
</script>
<th:block th:include="include :: footer"/>
<th:block th:include="include :: businessJS"/>
<th:block th:include="include :: inlineJS"/>

<script th:inline="javascript">
    /*<![CDATA[*/
    var prefix = ctx + "business/productbasis",
        prefix2 = ctx + "base/company";

    var fields = [[${fields}]];
    var fieldsList = [[${fieldsList}]];
    var fieldsHiddenList = [[${fieldsHiddenList}]];
    var moduleTable = [[${moduleTable}]];
    var enableEdit = [[${enableEdit}]];
    var vType = [[${vType}]]
    // //母件表格基础信息
    // var gridColumns = [[${gridColumns}]];
    // //母件表格基础信息
    // var gridColumnsZJ = [[${gridColumnsZJ}]];
    // // 母件列表数据
    // var List=[];

    // //子件列表数据
    var List = [[${sonList}]];
    console.log("List",List)


    var tablecols = [[ //标题栏
        {align: 'center', title: '退货信息', colspan: 8}
        , {align: 'center', title: '库存信息', colspan: 4}
        , {align: 'center', title: '采购信息', colspan: 9}
        // , {align: 'center', title: '操作', width: 150, fixed: 'right', rowspan: 2, toolbar: "#barDh", type: "normal"}
    ], [
        {field: 'code', title: '商品编码', width: 100, totalRowText: '合计',}
        , {field: 'name', title: '商品名称', width: 150}
        , {field: 'sCode', title: '子件编码', width: 100}
        , {field: 'sName', title: '子件名称', width: 100}
        // , {field: 'refundFs', title: '母件退货数', width: 100, edit: 'text', totalRow: true}
        , {field: 'refunds', title: '子件退货数', width: 100,edit: 'text',  totalRow: true}
        , {field: 'refundCost', title: '子件退货总价', width: 100, totalRow: true}
        , {field: 'gCode', title: '采购公司编码', width: 100}
        , {field: 'gName', title: '采购公司简称', width: 150}

        , {field: 'stockQty', title: '子件库存数', width: 120, templet: '#stockQty'}
        , {field: 'warehouse', title: '仓库', width: 100}
        , {field: 'repository', title: '库区', width: 100}
        , {field: 'seat', title: '库位', width: 100}
        , {field: 'sNum', title: '子件采购数量', width: 100, totalRow: true}
        , {field: 'price', title: '子件采购单价', width: 100, totalRow: true}
        , {field: 'cost', title: '子件采购总价', width: 100, totalRow: true}
        // ,{field: 'supplierID', title: '供应商ID', width: 100}
        // ,{field: 'supplierName', title: '供应商名称', width: 100}
        , {field: 'pOrderGuid', title: 'pOrderGuid', hide: true}
        , {field: 'rkBid', title: 'rkBid', hide: true}
        , {field: 'rkGuid', title: 'rkGuid', hide: true}
        , {field: 'sBom', title: 'sBom', hide: true}
        , {field: 'kcGuid', title: 'kcGuid', hide: true}
        //   ,{field: 'county', title: 'specId88', width: 100}
    ]]

    var $, layer, form, table, nid, noTable;
    layui.use(['laydate', 'form', 'layer', 'jquery', 'util', 'element', 'upload', 'table'], function () {
        $ = layui.$, layer = layui.layer, form = layui.form, laydate = layui.laydate, util = layui.util, element = layui.element, upload = layui.upload, table = layui.table;
        beforeInit();//表单初始化之前的动作集合
        //初始化操作
        headcom3()
        nid = $('#nid').val()


        console.log(vType,123)
        //判断当前环节权限
        if (vType == 0){
            $('#costAll').removeClass('canntEdit').attr('readonly', false)
            $('#address').removeClass('canntEdit').attr('readonly', false)
            $('#salesReturnSum').addClass('canntEdit').attr('readonly', 'disabled')
        } else if (vType == 1) {
            $('#orderID').addClass('canntEdit').attr('disabled', 'disabled')
            $('#vZdbz').addClass('canntEdit').attr('disabled', 'disabled')
            $('#salesReturnSum').addClass('canntEdit').attr('readonly', 'disabled')
            $('select').attr('disabled', 'disabled');
            $('#sXF').removeClass('canntEdit').attr('readonly', false)
            $('#wLF').removeClass('canntEdit').attr('readonly', false)
            $('#kDF').removeClass('canntEdit').attr('readonly', false)
            $('#place').removeClass('canntEdit').attr('readonly', false)
            $('#trackingNumber').removeClass('canntEdit').attr('readonly', false)
            // $('#address').removeClass('canntEdit').attr('readonly', false)
            $.each(tablecols[1], function (i, v) {
                delete v['edit']
            })//移除表格编辑属性
        } else if (vType == 2) {
            // console.log("采购退货")
            $('#orderID').addClass('canntEdit').attr('disabled', 'disabled')
            $('#vZdbz').addClass('canntEdit').attr('disabled', 'disabled')
            $('select').attr('disabled', 'disabled');
            // $('#salesReturnSum').addClass('canntEdit').attr('readonly', 'disabled')
            $.each(tablecols[1], function (i, v) {
                delete v['edit']
            })//移除表格编辑属性
        } else if (vType == 3) {
            $('#orderID').addClass('canntEdit').attr('disabled', 'disabled')
            $('#vZdbz').addClass('canntEdit').attr('disabled', 'disabled')
            $('#salesReturnSum').addClass('canntEdit').attr('readonly', 'disabled')
            $('select').attr('disabled', 'disabled');
            $.each(tablecols[1], function (i, v) {
                delete v['edit']
            })//移除表格编辑属性
        } else {
            $('#salesReturnSum').addClass('canntEdit').attr('readonly', 'disabled')

        }
        form.render('select');


        // 保存按钮事件变化
        $(function () {
            $('.tp-save').attr('onclick', '')
            $('.tp-save').attr('lay-filter', 'btn-edit')
            $('.tp-save').attr('lay-submit', true)
        })
        // 保存操作
        form.on('submit(btn-edit)', function (data) {
            var is_return = false//是否中断保存
            fieldsList.map((v, i) => {
                if (v.fieldFrontRequired) {
                    if (!$('#' + v.fields).val()) {
                        layer.msg(v.fieldName + '不能为空')
                        is_return = true
                    }
                }
            })

            listData1.map((v, i) => {
				console.log('v',v,i,data.field.isRk)
				if (data.field.isRk != '0' &&  v.stockQty == null){
					layer.msg("请选择库存")
					is_return = true
				}
            	if(data.field.isRk != '0' && v.refunds>v.stockQty){
					layer.msg("退货数量不可超过可用库存数")
					is_return = true
				}
                v.iid = i + 1
            })
			if (is_return) return;
			$.modal.loading("正在处理中，请稍后...");
            $.post("/purchase/refund/editpost", {
                infoMap: JSON.stringify(data.field),
                infoItems: JSON.stringify(listData1),
                sonData: JSON.stringify(listData1)
            }, function (res) {
                $.modal.closeLoading()
                layer.msg(res.msg);
                if (res.code == 0) {
                    window.location.href = '/purchase/refund/edit?nid=' + res.data+ '&vType=' + vType;
                }
            });
        });
        form.on('submit(btn-add)', function (data) {
            var is_return = false//是否中断保存
            if (vType == 2 && $('#salesReturnSum').val()*1 != $('#costAll').val()*1){
                is_return = true
                layer.msg("入账金额不符,请确认");
                return
            }
            fieldsList.map((v, i) => {
                if (v.fieldFrontRequired) {
                    if (!$('#' + v.fields).val()) {
                        layer.msg(v.fieldName + '不能为空')
                        is_return = true
                    }
                }
            })

            listData1.map((v, i) => {
				if (data.field.isRk != '0' &&  v.stockQty == null){
					layer.msg("请选择库存")
					is_return = true
				}
            	if(data.field.isRk != '0' &&  v.refunds>v.stockQty){
					layer.msg("退货数量不可超过可用库存数")
					is_return = true
				}
                v.iid = i + 1
            })
			if (is_return) return;
			$.modal.loading("正在处理中，请稍后...");
            $.post("/purchase/refund/editpost", {
                infoMap: JSON.stringify(data.field),
                infoItems: JSON.stringify(listData1),
                sonData: JSON.stringify(listData1)
            }, function (res) {
                $.modal.closeLoading()
                layer.msg(res.msg);
                if (res.code == 0) {
                    window.location.reload();                }
            });
        });


        var listData1 = List ? List : []
        // var listData2=sonList ?sonList:[]
        // 初始化表格
        $.tablelist.init({
            elem: '#dhtable'
            , data: listData1
            , page: false
            , even: true
            , limit: 10
            , totalRow: true
            , cols: tablecols
            , toolbar: '#zjtoolbar'
            , defaultToolbar: [{title: '列设置', layEvent: 'fieldSet', icon: 'layui-icon-set'}]
            , height: '400'
            , done: function (res, curr, count) {
                listData1 = table.cache.dhtable;//每次重载都赋值更新表缓存
            }, success: function (a, b, c) {
            }
        });


        //母件表格操作
        table.on('tool(mjtable)', function (obj) {
            switch (obj.event) {
                case "del":
                    layer.confirm('是否确定删除', {btn: ['确定', '取消']}, function () {
                        layer.closeAll();
                        obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                        listData1 = table.cache.dhtable;
                        for (var i = 0; i < listData1.length; i++) if (!listData1[i] || listData1[i].length == 0) listData1.splice(i, 1);//删除一项
                        // reloadTable(listData1);
                    })
                    break;
            }
            ;
        });

        //监听单元格编辑
        table.on('edit(mjtable)', function (obj) {
        	var v = obj.value
            if (obj.field === 'refunds') {
            	if(data.field.isRk != '0' && obj.value > obj.data.stockQty){
					v = obj.data.stockQty
					layer.msg('退货数量不可超过库存数')
				}

            	var x = v * obj.data.price;
                // console.log(obj.data,996,v)
                obj.data.refunds = v
                obj.update({refundCost:x.toFixed(2),refunds:obj.data.refunds});
            }
        });


        $(".fieldsimg").each(function () {
            var id = $(this).attr('name')
            upload.render({
                elem: '#' + id + '_upimg',
                url: '/system/fileinfo/uploadmailimg',
                accept: 'images',
                before: function (obj) {
                    //预读本地文件示例，不支持ie8
                    obj.preview(function (index, file, result) {
                        console.log(index, file, result)
                    });
                },
                done: function (res) {
                    //如果上传失败
                    if (res.errno > 0) {
                        return layer.msg('上传失败');
                    } else {
                        layer.msg('上传成功');
                        $('#' + id).val(res.data[0])
                        layui.$('#' + id + '_upimg').find('.upicon').addClass('layui-hide')
                        layui.$('#' + id + '_upimg').find('#uploadDemoView').removeClass('layui-hide').find('img').attr('src', res.data[0]);
                    }
                }, error: function (err) {
                    //演示失败状态，并实现重传
                    console.log(err)
                }
            });
        })


        $('.t_date').each(function () {
            var datetype = $(this).attr('datetype')
            laydate.render({
                elem: this
                ,
                type: datetype == 't_date' ? 'date' : datetype == 't_datetime' ? 'datetime' : datetype == 't_year' ? 'year' : 'month'
            })
        })

        $.get("/purchase/purchaseplan/listbynid?nid=" + nid, function (res) {
            noTable = res.data;
        });

    });

    function getMoreAfter(fieldsList, fields, tindex, fieldName, fieldSearchType, isSearch, isLayer, res) {//弹出框赋值回调
        if (fields == 'stockQty') {
            var listData = table.cache.dhtable
            listData[tindex].warehouse = res.gDepot
            listData[tindex].repository = res.vKq
            listData[tindex].seat = res.vHw
            listData[tindex].rkBid = res.rkBid
            listData[tindex].rkGuid = res.rkGuid
            listData[tindex].kcGuid = res.guid
            listData[tindex].stockQty = res.productNum
            table.reload('dhtable', {data: listData});
        } else if (fields == 'orderID') {
            var orderID = $('#orderID').val()
            $.get("/purchase/purchaseorder/selectrefundlist?bid=" + orderID, function (res2) {
                res2.data.map((v, i) => {
                    if (!v.refundCost) v.refundCost = 0
                    if (!v.refunds) v.refunds = 0
                    // if (!v.refundFs) v.refundFs = 0
                    if (v.guid) v.guid = ""
                })
                table.reload('dhtable', {data: res2.data});
            });
        }

    }


</script>

</body>
</html>